using Microsoft.AspNetCore.Mvc;
using System.Diagnostics;

namespace 基于WebApi的异步编程.Controllers
{
    [ApiController]
    [Route("[controller]/[action]")]
    public class WeatherForecastController : ControllerBase
    {
        private static readonly string[] Summaries = new[]
        {
        "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
    };

        private readonly ILogger<WeatherForecastController> _logger;

        public WeatherForecastController(ILogger<WeatherForecastController> logger)
        {
            _logger = logger;
        }

        [HttpGet(Name = "GetWeatherForecast")]
        public IEnumerable<WeatherForecast> Get()
        {
            return Enumerable.Range(1, 5).Select(index => new WeatherForecast
            {
                Date = DateTime.Now.AddDays(index),
                TemperatureC = Random.Shared.Next(-20, 55),
                Summary = Summaries[Random.Shared.Next(Summaries.Length)]
            })
            .ToArray();
        }

        [HttpGet]
        public async Task<int> Get123()
        {
            Process process = Process.GetCurrentProcess();//获取当前进程对象
            var ThreadCount = process.Threads.Count;//获取当前使用的线程总数
            Console.WriteLine(ThreadCount);//输出当前系统线程总数
            await Task.Delay(3000);//线程休眠，阻塞线程
            return await Task.FromResult(123);
        }

        [HttpGet]
        public async Task<int> Get456()
        {
            Process process = Process.GetCurrentProcess();//获取当前进程对象
            var ThreadCount = process.Threads.Count;//获取当前使用的线程总数
            Console.WriteLine(ThreadCount);//输出当前系统线程总数
            await Task.Delay(3000);//线程休眠，阻塞线程
            return await Task.FromResult(456);
        }


        [HttpGet]
        public async Task<int> Get789()
        {
            Process process = Process.GetCurrentProcess();//获取当前进程对象
            var ThreadCount = process.Threads.Count;//获取当前使用的线程总数
            Console.WriteLine(ThreadCount);//输出当前系统线程总数
            await Task.Delay(3000);//创建延迟任务，不会阻塞线程，异步出让线程使用
            //Thread.Sleep(3000);//线程休眠，阻塞线程
            return await Task.FromResult(789);
        }

        [HttpPost]
        public async Task test()
        {
            //在webapi中，每一个接口请求都有一个线程来处理，当调用此接口时，接口内依次调用的三个另外的接口如果是用Thread.sleep（）休眠阻塞线程，那么处理此次接口请求的线程被阻塞，体现出的效果就是三个异步方法以类似于同步的方式运行了，而如果另外三个接口是用await Task.Delay（），那么就是创建一个延迟任务，await出让线程，那么处理此次接口的线程可以继续去处理其他的任务，这才是异步的正确用法。
            var a=Get123();
            var b=Get456();
            var c=Get789();
            await Task.WhenAll(a, b, c);
        }
    }
}